<?php
/**
 * gpa_new Description
 * @package
 * @name controller
 * @filesource controller.php
 * @author Meta Sanjaya
 */

class controller_user extends Controller
{
    private $_self_profile = true;
    private $_user_menus = '';
    private $_main_menus = '';
    /**
     * @access public
     * @method __construct
     * @param void
     * @return void
     */
    public function  __construct() {
        parent::__construct();
        
        $model_menu = $this->getModel('menu');
        $this->_main_menus = createMenus($model_menu->getMenus());
        $this->_user_menus = createUserMenus();
    }

    public function register()
    {
        if(User::getUserId()) {
            redirect(getAppUrl('user', 'profile'), false);
        }
        
        if(count(getInstance('request')->post)) {
            $post = getInstance('request')->post;
            $files = array();
            
            if(count(getInstance('request')->files)) {
                $files = getInstance('request')->files;
            }

            $datas['post'] = $post;
            $datas['files'] = $files;

            //var_dump($datas);
            //exit;

            $model = $this->getModel();
            if(@$model->newUser($datas)) {
                redirect('user/success/register');
            }
        }

        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['page_title']="Registration Form";
        $this->addVars($var);
        $this->renderView('register_html');
    }

    public function login()
    {
        if(User::getUserId()) {
            redirect(getAppUrl('user', 'profile'), false);
        }

        $post = getInstance('request')->post;

        if(count($post)) {
            $model = $this->getModel('user');
            if($model->isRegistered($post['login_user'])) {
                if($model->isActive($post['login_user'])) {
                    if($model->checkPass($post['login_user'], $post['login_pass'])) {
                        User::setSession($model->getUserBy('username', $post['login_user']));
                        redirect('user/profile');
                        //$var['error_message'] = ;
                        //var_dump($model->getUserBy('username', $post['login_user']));
                    } else {
                        $var['error_message'] = "Username and Password did not match!";
                    }
                } else {
                    $var['error_message'] = "Your Account is Inactive. Please contact administrator";
                }
            } else {
                $var['error_message'] = "You are not registered here. Please register first";
            }
        } else {
            $var['error_message'] = "";
        }


        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['page_title']="Login Form";
        $this->addVars($var);
        $this->renderView('login_html');
    }

    public function forgot_pass() {
        $post = getInstance('request')->post;

        if(count($post) && isset($post['email_lost'])) {
            $model = $this->getModel('user');
            if(!@$model->forget_pwd($post['email_lost'])) {
                $var['error_message'] = "Email wrong or you haven't registered yet!";
            }
        } else {
            $var['error_message'] = "Email Not Found!";
        }

        $var['email'] = @$post['email_lost'];
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['page_title']="Forgot Password";
        $this->addVars($var);
        $this->renderView('forgot_pass_html');
        
    }

    public function edit()
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $var['response'] = '';
        $model = $this->getModel('user');

        if(count(getInstance('request')->post)) {
            $post = getInstance('request')->post;
            $files = array();

            if(count(getInstance('request')->files)) {
                $files = getInstance('request')->files;
            }

            $datas['post'] = $post;
            $datas['files'] = $files;

            //var_dump($datas);
            //exit;

            $model->editUser($datas);
            $var['response'] = 'data saved!';
        }

        $var['page_title']="Edit Profiles";
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $var['user_datas'] = User::getSession();
        $this->addVars($var);
        $this->renderView('edit_html');
    }

    public function tools()
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $model = $this->getModel();
        
        $var['page_title']="My Tools";
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $var['tools'] = $model->getTools();
        $this->addVars($var);
        $this->renderView('tools_html');
    }

    public function albums()
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $user = User::getSession();
        $model_album = $this->getModel('album');

        $var['page_title']="Albums";
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $var['albums'] = $model_album->getAlbums(User::getUserId());
        $var['user_name'] = $user['nickname'];
        $var['error_message'] = getInstance('session')->get('error_message');
        getInstance('session')->set('error_message', '');
        $this->addVars($var);
        $this->renderView('albums_html');
    }

    public function album($param)
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $user = User::getSession();
        $model_album = $this->getModel('album');
        if($album = @$model_album->getAlbum($param[0])) {
            if(@$album['private']) {
                if($user['user_id'] != $album['user_id']) {
                    trigger_error("This Album is Private!");
                    exit;
                }
            }

            $var['page_title']= $user['nickname'] . '\'s Album: ' . $album['album_name'];
            $var['mainmenus'] = $this->_main_menus;
            $var['usermenus'] = $this->_user_menus;
            $var['self_profile'] = $this->_self_profile;
            $var['album'] = $album;
            $var['user_name'] = $user['nickname'];
            $var['error_message'] = getInstance('session')->get('error_message');
            getInstance('session')->set('error_message', '');

            //var_dump($var);
            //exit;

            $this->addVars($var);
            $this->renderView('album_html');
        } else {
            redirect('user/albums');
        }
    }

    public function add_album() {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        if($datas = getInstance('request')->post) {
            if(empty($datas['album_name'])) {
                $datas['album_name'] = "No Name";
            }

            $datas['user_id'] = User::getUserId();
            $model = $this->getModel('album');
            if(!$model->addAlbum($datas)) {
                getInstance('session')->set('error_message', 'Cannot Create Album or Album is exists!');
            }
        }

        redirect('user/albums');
    }

    public function delete_album($param) {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $model_album = $this->getModel('album');
        if(!$model_album->removeAlbum($param[0])) {
            getInstance('session')->set('error_message', 'Cannot Delete Album!');
        }

        redirect('user/albums');
    }

    public function rename_album($param) {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $post = getInstance('request')->post;

        if(!empty($post['album_name'])) {
            $model_album = $this->getModel('album');
            if(!$model_album->renameAlbum($param[0], $post['album_name'])) {
                getInstance('session')->set('error_message', 'Cannot Rename Album!');
            }
        }

        redirect('user/album/'.$param[0]);
    }

    public function upload_photo($param) {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        if($datas = @getInstance('request')->files['upload_file']) {
            $datas = array_merge($datas, getInstance('request')->post);
            $datas['user_id'] = User::getUserId();
            $datas['album_id'] = $param[0];
            $datas['published'] = 0;

            if($datas['scope']=="screening") {
                $datas['published'] = 1;
            }

            if(empty($datas['title'])) {
                $datas['title'] = 'Untitled';
            }

            $datas['desc'] = "";
            $datas['cats'] = array();
            $datas['tags'] = array();
            $datas['info'] = array();

            //var_dump($datas);
            //exit;

            if(isset($datas['tmp_name'])) {
                if($exif = @exif_read_data($datas['tmp_name'])) {
                    if($exif['FileSize'] < (170*1024)+1) {
                        if($exif["MimeType"] == "image/jpeg") {
                            $datas['info']['location'] = "";
                            $datas['info']['date'] = "";
                            $datas['info']['camera'] = "";
                            $datas['info']['lens'] = "";
                            $datas['info']['filter'] = "";
                            $datas['info']['speed'] = "";
                            $datas['info']['diafragma'] = "";
                            $datas['info']['nude'] = 0;

                            if(isset($exif['Make'])) {
                                $datas['info']['camera'] = $exif['Make'] . " ";
                            }

                            if(isset($exif['Model'])) {
                                $datas['info']['camera'] .= $exif['Model'];
                            }

                            if(isset($exif['DateTime'])) {
                                $datas['info']['date'] = $exif['DateTime'];
                            }

                            $model = $this->getModel('gallery');

                            if($iid = $model->addImage($datas)) {
                                redirect('user/edit_image/' . $iid);
                            } else {
                                @unlink($datas['tmp_name']);
                                getInstance('session')->set('error_message', 'Unknown Error');
                            }
                        } else {
                            @unlink($datas['tmp_name']);
                            getInstance('session')->set('error_message', 'File Not a JPEG Image');
                        }
                    } else {
                        @unlink($datas['tmp_name']);
                        getInstance('session')->set('error_message', 'File Size more than 170Kb');
                    }
                } else {
                    @unlink($datas['tmp_name']);
                    getInstance('session')->set('error_message', 'That is not Image File');
                }
            } else {
                getInstance('session')->set('error_message', 'File Not Found!');
            }
        } else {
            getInstance('session')->set('error_message', 'Image Not Uploaded!');
        }

        redirect('user/album/' . $param[0]);
    }

    public function edit_image($param) {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }
        
        $iid = intval($param[0]);

        $model_album = $this->getModel('album');
        $model_gallery = $this->getModel('gallery');
        $model_category = $this->getModel('category');

        if(!$model_album->isUserImage($iid)) {
            trigger_error("You not authorized to edit this image!");
            exit;
        }

        if($post = getInstance('request')->post) {
            //var_dump($post);
            //exit;
            
            if(!isset($post['published'])) {
                $datas['published'] = 0;
            } else {
                $datas['published'] = 1;
            }

            if($post['scope']=='screening') {
                $datas['published'] = 1;
            }

            if(!empty($post['tags'])) {
                $tags = explode(",", $post['tags']);
            } else {
                $tags = array();
            }

            if(!isset($post['categories'])) {
                $post['categories'] = array();
            }

            if(!isset($post['info'])) {
                $post['info'] = array();
            }

            $datas['title'] = $post['title'];

            $model_gallery->setImage($iid, $datas);
            $model_gallery->setImageDescription($iid, $post['desc']);
            $model_gallery->setImageTags($iid, $tags);
            $model_gallery->setImageCategories($iid, $post['categories']);
            $model_gallery->setImageInfo($iid, $post['info']);

            header("user/edit_image/" . $iid );
        }

        $option['thumb_size'] = 600;
        $option['published_search'] = false;
        $image = $model_gallery->getImageById($iid, $option);

        $var['page_title'] = @$image['title'];
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $var['image'] = $image;
        $var['categories'] = $model_category->getCategories();
        $var['album_id'] = $model_album->getAlbumIdFromImageId($iid);
        $var['not_selected'] = $model_album->getNotSelectedAlbum(User::getUserId());
        $var['albums'] = $model_album->getAlbums(User::getUserId());

        //var_dump($image);
        //exit;

        $this->addVars($var);
        $this->renderView('edit_image_html');
    }

    public function messages($param)
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $var['page_title']="Messages";
        $view = 'messages_html';

        if(isset($param[0])) {
            switch($param[0]) {
                case "new":
                    
                break;
                default:
                case "inbox":
                    if($mid = @intval($param[1])) {
                        $model_message = $this->getModel('message');
                        $messages = $model_message->getMessage($mid);

                        if(count($messages)) {
                            $model_user = $this->getModel('user');
                            $var['page_title']=$messages[0]['subject'];
                            $from_id = $model_message->getMessageUser($mid);
                            if(count($from_id)) {
                                $from = $model_user->getUserBy('user_id', $from_id[0]['from_user_id']);
                                if(count($from)) {
                                    $messages[0]['from'] = $from['username'];
                                } else {
                                    $messages[0]['from'] = "Unknown";
                                }
                            }
                            $var['message']=$messages[0];
                        } else {
                            $var['page_title']="No Message!";
                        }

                        $view = 'message_html';
                    } else {
                        redirect('user/messages');
                    }
                break;
            }
        } else {
            $model_message = $this->getModel('message');
            $var['messages'] = $model_message->getUserMessages(User::getUserId());
        }

        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $this->addVars($var);
        $this->renderView($view);
    }

    public function avatar()
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $model = $this->getModel();
        $post = getInstance('request')->post;
        $datas = getInstance('request')->files;

        if(count($post) && count($datas)) {
            $datas = $datas['avatar'];
            //var_dump($datas);
            //exit;
            if($datas['size'] < (30*1024)+1) {
                if($datas["type"] == "image/jpeg") {
                    $model->setAvatar($datas);
                } else {
                    @unlink($datas['tmp_name']);
                    getInstance('session')->set('error_message', 'File Not a JPEG Image');
                }
            } else {
                @unlink($datas['tmp_name']);
                getInstance('session')->set('error_message', 'File Size is more than 30KB');
            }

            redirect(getAppUrl(), false);
        }

        if($ua = $model->getAvatar(User::getUserId())) {
            $var['user_avatar'] = getImgUrl() . "user/avatar/" . $ua;
        }
        
        $var['page_title']="Your Avatar";
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $var['error_message'] = @getInstance('session')->get('error_message');
        getInstance('session')->set('error_message', "");

        $this->addVars($var);
        $this->renderView('avatar_html');
    }

    public function profile($param)
    {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $session = User::getSession();
        
        if(isset($session['username'])) {
            if(!isset($param[0])) {
                $param[0] = $session['username'];
            }
            
            if($session['username'] == $param[0]) {
                $this->_self_profile = true;
            } else {
                $this->_self_profile = false;
            }
        }

        $var['page_title']="Profile " . $param[0];
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;
        $this->addVars($var);
        $this->renderView('profile_html');
    }

    public function upgrade() {
        if(!User::getUserId()) {
            redirect(getAppUrl('user', 'login'), false);
        }

        $var['page_title']="Upgrade Account";
        $var['mainmenus'] = $this->_main_menus;
        $var['usermenus'] = $this->_user_menus;
        $var['self_profile'] = $this->_self_profile;

        $this->addVars($var);
        $this->renderView('upgrade_html');
    }

    public function success($param) {
        $var['mainmenus'] = $this->_main_menus;
        $var['page_title']="Congrats!!";
        $this->addVars($var);
        switch ($param[0]) {
            case 'register':
                if(@getInstance('config')->get('email_validation')) {
                    $this->renderView('success_register_validation_html');
                } else {
                    $this->renderView('success_register_html');
                }
            break;
            case 'validation':
                $this->renderView('success_validation_html');
        }
    }

    public function email_validation($param) {
        $model = $this->getModel();
        if(@$model->validateUser($param[0], $param[1])) {
            redirect('user/success/validation');
        }
    }

    public function logout() {
        User::signOut();
        redirect(getHttpUrl(), false);
    }

    public function __default()
    {
        redirect('user/login');
    }
}
?>